package la.renzhen.rtpt.config.source;

import la.renzhen.rtpt.config.ConfigurationSource;
import la.renzhen.rtpt.config.Reloadable;
import la.renzhen.rtpt.spring.events.ReloadApplicationEvent;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;

@Slf4j
public class SpringConfigurationSource implements Reloadable, ConfigurationSource, ApplicationContextAware {

    @Setter
    ApplicationContext applicationContext;

    @Getter
    ConfigurationSource configurationSource;

    public SpringConfigurationSource(ConfigurationSource sources) {
        this.configurationSource = sources;
    }

    public void reload() {
        if (configurationSource instanceof Reloadable) {
            ((Reloadable) configurationSource).reload();
        }
        log.info("reload configuration");
        applicationContext.publishEvent(new ReloadApplicationEvent(this));
    }

    @Override
    public Map<String, String> loadAll(String environment, String prefix) {
        return configurationSource.loadAll(environment, prefix);
    }

    @Override
    public String get(String environment, String key) {
        return configurationSource.get(environment, key);
    }
}